$(function(){
	var obj = {
		id : 0,								//商品id
		total : 0,							//总价钱		
		name : $('.Name'),					//姓名
		tel : $('.telephone'),				//联系方式
		Province : $('.province'),			//省
		City : $('.city'),					//市
		Area : $('.area'),					//区
		title : $('.name'),					//商品名称
		price : $('.price'),				//商品价格
		img : $('.img'),					//商品缩略图
		goodNum : $('.goodsNum'),			//商品数量加减处的商品数量
		orderNum : $('.orderNum'),			//订单信息处的商品数量
		footTotal : $('.balance'),			//底部的总价钱
		paymentTotal : $('.paymentTotal'),	//支付窗口的总价值
		adressId : 0						//收货地址ID	
	}
	
	function loadPage(){
		showData();		//进入页面立即执行，加载商品信息
		if(localStorage.getItem('data')){
			var adressData = JSON.parse(localStorage.getItem('data'));
			console.log(adressData);
			obj.name.text(adressData.name);
			obj.tel.text(adressData.tel);
			obj.Province.text(adressData.sheng);
			obj.City.text(adressData.shi);
			obj.Area.text(adressData.qu);
			obj.adressId = adressData.id;
			pay();	//如果地址存在才可以使用下单功能
		}else{
			promptlyLoad();
			pay();	//如果地址存在才可以使用下单功能
		}
	}
	loadPage();     //进入页面加载地址
	
	//加载商品信息
	function showData(){
		obj.id = localStorage.getItem('lgId');
		obj.title.text(localStorage.getItem('title'));
		obj.price.text(localStorage.getItem('price'));
		obj.img.attr("src",localStorage.getItem('src'));
		obj.goodNum.val(localStorage.getItem('num'));
		obj.orderNum.text(localStorage.getItem('num'));
		obj.total = ((obj.price.text() - 0) * (obj.orderNum.text() - 0)).toFixed(2);
		obj.footTotal.text(obj.total);
	}
	
	//加载地址信息
	function promptlyLoad(){
		$.ajax({
			type:"post",
			url:"http://a.91jfk.com/Product/Address/address_default",
			dataType:'json',
			success:function(res){
				console.log(res);
				if(res.code == '1'){
					var data = res.msg;
					obj.adressId = data.id;
					obj.name.text(data.name);
					obj.tel.text(data.tel);
					obj.Province.text(data.area);
					obj.City.text(data.street);
					obj.Area.text(data.address);
				} else {
					$(".errAlert").text("请添加地址...").addClass("AlertShow");
					setTimeout(function() {
						$(".errAlert").removeClass("AlertShow");
					}, 3000);
				}
			},
			error:function(err){
				console.log(err)
			}
		});
	}	
	
	//点击顶部跳转编辑地址页面
	$('.cfmOrder_content').undelegate().delegate('.address','click',function(){
		window.location.href = 'guanlidizhi.html';
	});
	
	//商品数量加减
    function addORreduce(){
	    //数量加按钮  
	    $(".buy_num .add").click(function(){  
	    	obj.orderNum.text(parseInt(obj.orderNum.text() - 0) + 1);
	        obj.goodNum.val(parseInt(obj.goodNum.val()) + 1);
	        obj.total = ((obj.price.text() - 0) * (obj.goodNum.val() - 0)).toFixed(2);
	        obj.footTotal.text(obj.total);
	        console.log(obj.total);
	        $(".buy_num .reduce").removeAttr("disabled");           //当按加1时，设置$(".buy_num .reduce")为可点击状态
	    });
	    //数量减按钮  
	    $(".buy_num .reduce").click(function(){  
	        if (parseInt(obj.goodNum.val()) > 1) {                 	//判断数量值大于1时才可以减少  
	        	obj.orderNum.text(parseInt(obj.orderNum.text() - 0) - 1);
	        	obj.goodNum.val(parseInt(obj.goodNum.val()) - 1);
	        	obj.total = ((obj.price.text() - 0) * (obj.goodNum.val() - 0)).toFixed(2);
	        	obj.footTotal.text(obj.total);
	        	console.log(obj.total);
	        }else{  
	        	$(".buy_num .reduce").attr("disabled",true);  		//当num为1时，设置$(".buy_num .reduce")为不可点击状态
	        	$(".errAlert").text("商品数量至少为一件").addClass("AlertShow");
	        	setTimeout(function(){
		        	$(".errAlert").removeClass("AlertShow");
		        },3000);  
	       	}
	    });
    }
    addORreduce();
    
    //点击确认下单按钮
    function pay(){
    	$('.cfmOrder_cfm').bind('click',function(){
	    	$('.cfmOrder_foot').css('display','none');
	    	$('.payment_foot').css('display','block');
	    	$('.mask').css('display','block');
	    	var FinalTotal = (($('.orderNum').text() - 0) * ($('.price').text() - 0)).toFixed(2);
	    	obj.paymentTotal.text(FinalTotal);
	    	console.log(FinalTotal,obj.footTotal.text());
	    	var Number = obj.orderNum.text();
	    	var id = obj.id;
	    	var adressId = obj.adressId;
	    	console.log(Number,id,adressId);
	    	if(FinalTotal == obj.footTotal.text()){	//如果付款弹窗的总金额与底部的总金额相等发送支付请求
	    		$.ajax({
		    		type:"post",
		    		url:"http://a.91jfk.com/Product/Zero/go_order",
		    		data:{
		    			id : id,
		    			num : Number,
		    			aid : adressId,
		    			platform : 1
		    		},
		    		success:function(res){
		    			console.log(res);
			    		if(res.code == 1){
			    			//点击圆圈选择支付方式
						    var payWay;		//用于记录支付方式
						    $('.mode_row').unbind('click').click(function(){
						    	$(this).children('.row_Rt').find('.pur').addClass('addCir');
						    	$(this).siblings().children('.row_Rt').find('.pur').removeClass('addCir');
						    	var a = $(this).children('input[type=hidden]').val();	//支付方式
						    	payWay = $(this).children('.row_con').find('.mode_name').text();
						    	console.log(payWay);
						    });
						    var orderId = res.orderid;
						    console.log(orderId);
						    //点击确认支付
						    $('.confirm_cfm').unbind('click').click(function(){
						    	if(payWay == '微信支付'){
						    		console.log('微信支付')
						    		$.ajax({
										url: "http://a.91jfk.com/Product/WxJsAPI/jsApiCall",
										type: "post",
										data: {
											orderId: orderId
										},
										datatype: "json",
										success: function(xhr) {
											console.log(xhr);
											var data = JSON.parse(xhr);
											callpay(data.jsApiParameters);
										},
										error: function(mes) {
											console.log('支付失败');
										}
									});//ajax结束
						    	}else if(payWay == '连连支付'){
						    		console.log('连连支付')
						    		//location.href = "../Lianlianpay/send/no_order/" + order; //连连接口
						    	}else{
						    		console.log('请选择付款方式...');
						    		$(".errAlert").text("请选择付款方式...").addClass("AlertShow");
						        	setTimeout(function(){
							        	$(".errAlert").removeClass("AlertShow");
							        },3000);
					    	    }
						    });
			    		}else{
			    			$(".errAlert").text(res.msg).addClass("AlertShow");
				        	setTimeout(function(){
					        	$(".errAlert").removeClass("AlertShow");
					        },3000);
			    		}
		    		},
		    		error:function(err){
		    			console.log(err);
		    		}
		    	});	//AJAX结束
	    	}else{
	    		console.log('错误...');
	    	}
	    });
    }
    //点击关闭按钮，关闭支付弹框
    $('.close').bind('click',function(){
    	$('.cfmOrder_foot').css('display','block');
    	$('.payment_foot').css('display','none');
    	$('.mask').css('display','none');
    });
    
    function callpay(arg) {
		if(typeof WeixinJSBridge == "undefined") {
			if(document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
			} else if(document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', jsApiCall);
				document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
			}
		} else {
			jsApiCall(arg);
		}
	}

	//调用微信JS api 支付
	function jsApiCall(arg) {
		var data = JSON.parse(arg);
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			data,
			function(res) {
				WeixinJSBridge.log(res.err_msg);
				if(res.err_msg == "get_brand_wcpay_request:ok") {
					localStorage.clear();
					//alert("支付成功");
				} else if(res.err_msg == "get_brand_wcpay_request:cancel") {
					//alert("取消支付");
				} else {
					//alert(res.err_msg);
					//alert("支付失败");
				}
			});
	}
//	window.onunload = function(){
//		localStorage.clear();
//	}
});
